﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using CommClass;
using DMS.CommClass;


namespace DMS
{
    public partial class FrmAddcaigouputong : DMS.FrmTemplate 
    {
        
        MO mo = new MO(App.Ds);
        CaigouDAO cg = new CaigouDAO(App.Ds);
        string mergenumber;
        int CaigouID11 = 0;
        int userid = 0;    
        string sqlstr;
        bool flag;
        public FrmAddcaigouputong(string CaigouID)  
        {
            InitializeComponent();
            //初始化列
            DataGridViewTextBoxColumn huowuzhonglei = new DataGridViewTextBoxColumn();
            huowuzhonglei.HeaderText = "商品种类";
            huowuzhonglei.CellTemplate = new DataGridViewTextBoxCell();
            huowuzhonglei.Name = "商品种类";
            huowuzhonglei.ReadOnly = true;
            this.dgvdo.Columns.Add(huowuzhonglei);

            DataGridViewLinkColumn huowumincheng = new DataGridViewLinkColumn();
            huowumincheng.HeaderText = "商品名称";
            huowumincheng.CellTemplate = new DataGridViewLinkCell();
            huowumincheng.Name = "商品名称";
            huowumincheng.ReadOnly = true;
            this.dgvdo.Columns.Add(huowumincheng);

            DataGridViewTextBoxColumn huowubianma = new DataGridViewTextBoxColumn();
            huowubianma.HeaderText = "商品编码";
            huowubianma.CellTemplate = new DataGridViewTextBoxCell();
            huowubianma.Name = "商品编码";
            huowubianma.ReadOnly = true;
            this.dgvdo.Columns.Add(huowubianma);


            DataGridViewTextBoxColumn shishoushuliang = new DataGridViewTextBoxColumn();
            shishoushuliang.HeaderText = "采购数量";
            shishoushuliang.CellTemplate = new DataGridViewTextBoxCell();
            shishoushuliang.Name = "采购数量";
           
            this.dgvdo.Columns.Add(shishoushuliang);

            DataGridViewTextBoxColumn caigoujia = new DataGridViewTextBoxColumn();
            caigoujia.HeaderText = "采购价";
            caigoujia.CellTemplate = new DataGridViewTextBoxCell();
            caigoujia.Name = "采购价";
           
            this.dgvdo.Columns.Add(caigoujia);

            DataGridViewTextBoxColumn dunwei = new DataGridViewTextBoxColumn();
            dunwei.HeaderText = "规格";
            dunwei.CellTemplate = new DataGridViewTextBoxCell();
            dunwei.Name = "规格";
            dunwei.ReadOnly = true;
            this.dgvdo.Columns.Add(dunwei);

            DataGridViewTextBoxColumn lifangmi = new DataGridViewTextBoxColumn();
            lifangmi.HeaderText = "吨位";
            lifangmi.CellTemplate = new DataGridViewTextBoxCell();
            lifangmi.Name = "吨位";
            lifangmi.ReadOnly = true;
            this.dgvdo.Columns.Add(lifangmi);

            

            DataGridViewColumn shangpinID = new DataGridViewColumn();
            shangpinID.HeaderText = "商品id";
            shangpinID.ReadOnly = true;
            shangpinID.CellTemplate = new DataGridViewTextBoxCell();
            shangpinID.Name = "商品id";
            shangpinID.Visible = false;
            this.dgvdo.Columns.Add(shangpinID);



            DataGridViewColumn InStockEntryID = new DataGridViewColumn();
            InStockEntryID.HeaderText = "明细id";
            InStockEntryID.CellTemplate = new DataGridViewTextBoxCell();
            InStockEntryID.Name = "明细id";
            InStockEntryID.ReadOnly = true;
            InStockEntryID.Visible = false;
            this.dgvdo.Columns.Add(InStockEntryID);

            DataGridViewColumn ProdTypeID = new DataGridViewColumn();
            ProdTypeID.HeaderText = "商品种类id";
            ProdTypeID.CellTemplate = new DataGridViewTextBoxCell();
            ProdTypeID.Name = "商品种类id";
            ProdTypeID.ReadOnly = true;
            ProdTypeID.Visible = false;
            this.dgvdo.Columns.Add(ProdTypeID);

            this.chengyunshang();
            this.getgongyingshang();
            this.gethuozhu();
            this.getcangku();
          

            //制单人
            textBox2.Text = App.AppUser.UserName;
            userid = App.AppUser.UserID;
            //如果传入了采购单id，就查询相应的采购单，并且赋值
            if (CaigouID != null && CaigouID != "")
            {
                this.Text = "修改采购单";
                DataTable dt = cg.GetCaigouupdate("a.CaigouID = " + CaigouID);
                if (dt.Rows.Count > 0)
                {
                    CaigouID11 = int.Parse(CaigouID);
                    
                    txtbOrderNumber.Text = dt.Rows[0]["CaigouNumber"].ToString();
                    comboBox1.SelectedValue = dt.Rows[0]["StoreID"].ToString();
                    cmbcarrierid.SelectedValue = dt.Rows[0]["CarrierID"].ToString();
                    textBox1.Text = dt.Rows[0]["TuiHuoKeHu"].ToString();
                    textBox3.Text = dt.Rows[0]["TuiHuoRemark"].ToString();
                   
                    comboBox2.SelectedValue = dt.Rows[0]["SupplierID"].ToString();
                    comboBox3.SelectedValue = dt.Rows[0]["SupplySupplierID"].ToString();
                    dateTimePicker1.Text = dt.Rows[0]["CaigouDate"].ToString();
                    textBox2.Text = dt.Rows[0]["UserName"].ToString();
                    userid = int.Parse(dt.Rows[0]["UserID"].ToString());
                    txtbProduct.Text = dt.Rows[0]["Remark"].ToString();
                    textBox3.Text = dt.Rows[0]["TuiHuoRemark"].ToString();
                }
                DataTable dtt  = cg.GetCaigouEntry("a.CaigouID = " + CaigouID); 
                if (dtt.Rows.Count > 0)
                {
                    //品质下拉
                    DataTable dtttt = mo.GetStockPinZhi();   
                    DataRow dr = dtttt.NewRow();
                    dr["StockPinZhiID"] = "0";
                    dr["StockPinZhiMiaoShu"] = "请选择";     
                    dtttt.Rows.InsertAt(dr, 0);
                    
                    for (int i = 0; i < dtt.Rows.Count; i++)
                    {
                        int t = this.dgvdo.Rows.Add();
                        this.dgvdo.Rows[t].Cells["商品种类"].Value = dtt.Rows[i]["商品种类"].ToString();
                        
                        this.dgvdo.Rows[t].Cells["商品名称"].Value = dtt.Rows[i]["商品名称"].ToString();

                        this.dgvdo.Rows[t].Cells["商品编码"].Value = dtt.Rows[i]["商品编码"].ToString();

                        this.dgvdo.Rows[t].Cells["采购数量"].Value = dtt.Rows[i]["采购数量"].ToString();
                        this.dgvdo.Rows[t].Cells["采购价"].Value = dtt.Rows[i]["采购价"].ToString();
                        this.dgvdo.Rows[t].Cells["规格"].Value = dtt.Rows[i]["规格"].ToString();

                        this.dgvdo.Rows[t].Cells["吨位"].Value = dtt.Rows[i]["吨位"].ToString();



                        this.dgvdo.Rows[t].Cells["商品id"].Value = dtt.Rows[i]["商品id"].ToString();

                        this.dgvdo.Rows[t].Cells["明细id"].Value = dtt.Rows[i]["明细id"].ToString();
                        this.dgvdo.Rows[t].Cells["商品种类id"].Value = dtt.Rows[i]["商品种类id"].ToString();

                    }
                }
            }

        }


        //定义传递提单号
        private string sedonumber = null;
        public string SeDoNumber
        {
            get
            {
                return sedonumber;
            }
        }

     
        
       
        private void chengyunshang()
        {
            //承运商下拉
            DataTable dt = mo.GetCarrierID();
            DataRow dr = dt.NewRow();
            dr["CarrierID"] = "0";
            dr["CarrierName"] = "请选择";
            dt.Rows.InsertAt(dr, 0);
            //下拉数据绑定
            cmbcarrierid.DataSource = dt;
            cmbcarrierid.DisplayMember = "CarrierName";
            cmbcarrierid.ValueMember = "CarrierID";
            //默认选中
            cmbcarrierid.SelectedIndex = 1;

        }
     
        private void getcangku() 
        {
            //仓库下拉
            DataTable dt = mo.getcangku();
            DataRow dr = dt.NewRow();
            dr["StoreID"] = "0";
            dr["StoreName"] = "请选择";
            dt.Rows.InsertAt(dr, 0);
            //下拉数据绑定
            comboBox1.DataSource = dt;
            comboBox1.DisplayMember = "StoreName";
            comboBox1.ValueMember = "StoreID";
            //默认选中
            comboBox1.SelectedIndex = 1;

        }

        private void gethuozhu()
        {
            //货主下拉
            DataTable dt = mo.gethuozhu();
            DataRow dr = dt.NewRow();
            dr["SupplierID"] = "0";
            dr["SupplierName"] = "请选择";
            dt.Rows.InsertAt(dr, 0);
            //下拉数据绑定
            comboBox2.DataSource = dt;
            comboBox2.DisplayMember = "SupplierName";
            comboBox2.ValueMember = "SupplierID";
            //默认选中
            comboBox2.SelectedIndex = 1;

        }


        private void getgongyingshang()
        {
            //供应商下拉
            DataTable dt = mo.getgongyingshang();
            DataRow dr = dt.NewRow();
            dr["SupplySupplierID"] = "0";
            dr["SupplySupplierName"] = "请选择";
            dt.Rows.InsertAt(dr, 0);
            //下拉数据绑定
            comboBox3.DataSource = dt;
            comboBox3.DisplayMember = "SupplySupplierName";
            comboBox3.ValueMember = "SupplySupplierID";
            //默认选中
            comboBox3.SelectedIndex = 1;

        }

       



        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) 
        {
            if (e.ColumnIndex == -1 || e.RowIndex == -1) return;

          
                    if (e.ColumnIndex == 2)
                    {
                        if (comboBox3.SelectedIndex == 0)
                        {
                            MessageBox.Show("请选择供应商！");
                            return;
                        }
                        if (comboBox2.SelectedIndex == 0)
                        {
                            MessageBox.Show("请选择货主！");
                            return;
                        }
                        FrmAddcaigouProduct formap = new FrmAddcaigouProduct(dgvdo.Rows[e.RowIndex], comboBox3.SelectedValue.ToString(), comboBox2.SelectedValue.ToString());
                        formap.ShowDialog();
                           
                    }

        }

        private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            //查看提单明细信息
           // int row = dgvdo.Rows[e.RowIndex].Index;
           // sedonumber = dgvdo.Rows[row].Cells[1].Value.ToString();//当前选定的提货单号
          //  FrmDoEntry form = new FrmDoEntry();
          //  form.ReDoNumber = sedonumber;
           // form.ShowDialog();
        }

        private void button4_Click(object sender, EventArgs e)
        {
        
            if (dgvdo != null && dgvdo.RowCount > 0)
            {
                DataGridViewCheckBoxCell checkCell;
                for (int i = 0; i < dgvdo.RowCount; i++)
                {
                    //判断是否选中
                    checkCell = (DataGridViewCheckBoxCell)this.dgvdo.Rows[i].Cells[0];

                    checkCell.Value = true;

                }
              
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (dgvdo != null && dgvdo.RowCount > 0)
            {
                DataGridViewCheckBoxCell checkCell;
                for (int i = 0; i < dgvdo.Rows.Count; i++)
                {
                    //判断是否选中
                    checkCell = (DataGridViewCheckBoxCell)this.dgvdo.Rows[i].Cells[0];

                    checkCell.Value = false;

                }
              
            }
        }



        private void button6_Click_1(object sender, EventArgs e)
        {
            int t = this.dgvdo.Rows.Add();
            this.dgvdo.Rows[t].Cells["商品名称"].Value = "请点击";

        }

        private void button7_Click(object sender, EventArgs e)
        {
            CaigouEntry cae = new CaigouEntry();
            using (SqlConnection conn = new SqlConnection(App.GetSqlConnection()))
            {
                conn.Open();
                using (SqlTransaction tran = conn.BeginTransaction()) //开始数据库事务。即创建一个事务对象tran  
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        cmd.Connection = conn;
                        cmd.Transaction = tran; //获取或设置将要其执行的事务  
                        try
                        {
                           

            for (int i = 0; i < dgvdo.RowCount; i++)
            {
                //判断是否选中
                if (dgvdo.Rows[i].Cells[0].EditedFormattedValue.ToString() == "True")
                {
                    if (this.dgvdo.Rows[i].Cells["明细id"].Value != null && this.dgvdo.Rows[i].Cells["明细id"].Value.ToString() != "")
                    {
                        cae.deleteCaigouEntry(" CaigouEntryID = " + this.dgvdo.Rows[i].Cells["明细id"].Value.ToString(), conn, cmd);
                    }
                    dgvdo.Rows.Remove(dgvdo.Rows[i]);
                    i -= 1;
                }

            }

            tran.Commit();
            conn.Close();
            
                        }
                        catch
                        {

                            tran.Rollback();//如果执行不成功，发送异常，则执行rollback方法，回滚到事务操作开始之前。
                            conn.Close();
                            MessageBox.Show("保存失败");
                        }

                    }
                }

            }
        }

      

        private void button1_Click(object sender, EventArgs e)
        {
            //验证数据
            StringBuilder message = new StringBuilder();
            if (this.dgvdo.RowCount == 0)
            {
                MessageBox.Show("请添加商品！ ");
                return;
            }
            //判断物料重复
            for (int i = 0; i < this.dgvdo.RowCount; i++)
            {
                for (int j = i+1; j < this.dgvdo.RowCount; j++)
                {

                    if (dgvdo.Rows[i].Cells["商品id"].Value.ToString() == dgvdo.Rows[j].Cells["商品id"].Value.ToString())
                    {
                        MessageBox.Show( "第" + (i + 1) + "行与第" + (j + 1) + "行重复！ " );
                        return;
                    }
                }
            }
            
            if (comboBox2.SelectedIndex == 0)
            {
                message.Append("请选择货主！\n ");
            }
            if (comboBox1.SelectedIndex == 0)
            {
                message.Append("请选择仓库！\n ");
            }
            if (comboBox3.SelectedIndex == 0)
            {
                message.Append("请选择供应商！\n ");
            }
            if (cmbcarrierid.SelectedIndex == 0)
            {
                message.Append("请选择承运商！\n ");
            }



            //验证明细列表
            for (int i = 0; i < this.dgvdo.RowCount; i++)
            {
                if (dgvdo.Rows[i].Cells["商品id"].Value == null || dgvdo.Rows[i].Cells["商品id"].Value.ToString() == "")
                {
                    message.Append("第"+(i+1)+"行未选择商品！\n ");
                }
                Double ddd = 0;
                if (dgvdo.Rows[i].Cells["采购数量"].Value == null || dgvdo.Rows[i].Cells["采购数量"].Value.ToString() == "" || !Double.TryParse(dgvdo.Rows[i].Cells["采购数量"].Value.ToString(), out ddd))
                {
                    message.Append("第" + (i + 1) + "行采购数量请填写数字！\n ");

                }
                Double ddd1 = 0;
                if (dgvdo.Rows[i].Cells["采购价"].Value == null || dgvdo.Rows[i].Cells["采购价"].Value.ToString() == "" || !Double.TryParse(dgvdo.Rows[i].Cells["采购价"].Value.ToString(), out ddd1))
                {
                    message.Append("第" + (i + 1) + "行采购价请填写数字！\n ");

                }
            }
            if (message != null && message.ToString() != "")
            {
                MessageBox.Show(message.ToString());
                return;
            }
            //开始新增
  

                //Math.Round(45.367,2)  
                using (SqlConnection conn = new SqlConnection(App.GetSqlConnection()))
                {
                    conn.Open();
                    using (SqlTransaction tran = conn.BeginTransaction()) //开始数据库事务。即创建一个事务对象tran  
                    {
                        using (SqlCommand cmd = new SqlCommand())
                        {
                            cmd.Connection = conn;
                            cmd.Transaction = tran; //获取或设置将要其执行的事务  
                            try
                            {
                                Caigou cgd = new Caigou();

                               
                                cgd.ZhiDanDate = DateTime.Now;
                                cgd.CaigouDate = DateTime.Parse(dateTimePicker1.Text.Trim());
                                if (userid > 0)
                                {
                                    cgd.UserID = userid;
                                    cgd.CaigourenID = userid;
                                }
                                else
                                {
                                    cgd.UserID = App.AppUser.UserID;
                                    cgd.CaigourenID = App.AppUser.UserID;
                                }

                                cgd.CaigouTypeID = App.caigouputong;
                                cgd.CaigouStatusID = App.newstatus;
                                cgd.SupplierID = int.Parse(comboBox2.SelectedValue.ToString());
                                cgd.SupplySupplierID = int.Parse(comboBox3.SelectedValue.ToString());
                                cgd.CarrierID = int.Parse(cmbcarrierid.SelectedValue.ToString());
                                cgd.StoreID = int.Parse(comboBox1.SelectedValue.ToString());



                                cgd.TuiHuoKeHu = textBox1.Text.Trim();
                                cgd.TuiHuoRemark = textBox3.Text.Trim();
                                cgd.Remark = txtbProduct.Text.Trim();
                                if (CaigouID11 > 0)
                                {
                                    cgd.CaigouNumber = txtbOrderNumber.Text;
                                    cgd.CaigouID = CaigouID11;
                                    cgd.updateCaigou(cgd, conn, cmd);
                                }
                                else
                                {
                                    cgd.CaigouNumber = cgd.MakeCaigouNumber(conn, cmd);
                                    txtbOrderNumber.Text = cgd.CaigouNumber;
                                    cgd.CaigouID = cgd.saveCaigou(cgd, conn, cmd);
                                    CaigouID11 = cgd.CaigouID;
                                }
                                //插入明细
                                for (int i = 0; i < this.dgvdo.Rows.Count; i++)
                                {
                                    CaigouEntry cae = new CaigouEntry();
                                    cae.CaigouID = cgd.CaigouID;
                                    cae.ProdID = int.Parse(this.dgvdo.Rows[i].Cells["商品id"].Value.ToString());



                                    cae.CaigouShuLiang = double.Parse(this.dgvdo.Rows[i].Cells["采购数量"].Value.ToString());
                                    cae.Caigoujia = double.Parse(this.dgvdo.Rows[i].Cells["采购价"].Value.ToString());

                                    cae.Remark = "";

                                    if (this.dgvdo.Rows[i].Cells["明细id"].Value != null && this.dgvdo.Rows[i].Cells["明细id"].Value.ToString() != "")
                                    {
                                        cae.CaigouEntryID = int.Parse(this.dgvdo.Rows[i].Cells["明细id"].Value.ToString());
                                        cae.updateCaigouEntry(cae, conn, cmd);

                                    }
                                    else
                                    {
                                        int CaigouEntryid = cae.saveCaigouEntry(cae, conn, cmd);
                                        this.dgvdo.Rows[i].Cells["明细id"].Value = CaigouEntryid;
                                    }
                                   

                                }
                               

                                tran.Commit();
                                conn.Close();
                               
                                MessageBox.Show("保存成功");
                            }
                            catch
                            {

                                tran.Rollback();//如果执行不成功，发送异常，则执行rollback方法，回滚到事务操作开始之前。
                                conn.Close();
                                MessageBox.Show("保存失败");
                            }

                        }
                    }

                }
            
        }

        private void button8_Click(object sender, EventArgs e)
        {
            if (CaigouID11 == 0)
            {
                MessageBox.Show("请先保存！");
                return;
            }
            if (MessageBox.Show("是否删除?", "请确认信息", MessageBoxButtons.OKCancel) == DialogResult.OK)

           {

           //delete


               CaigouEntry cae = new CaigouEntry();
               Caigou cg = new Caigou();
            using (SqlConnection conn = new SqlConnection(App.GetSqlConnection()))
            {
                conn.Open();
                using (SqlTransaction tran = conn.BeginTransaction()) //开始数据库事务。即创建一个事务对象tran  
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        cmd.Connection = conn;
                        cmd.Transaction = tran; //获取或设置将要其执行的事务  
                        try
                        {


                            cae.deleteCaigouEntry(" CaigouID = " + CaigouID11, conn, cmd);
                            cg.deleteCaigou(" CaigouID = " + CaigouID11, conn, cmd);

                            tran.Commit();
                            conn.Close();
                            MessageBox.Show("删除成功");
                            this.Close();
                        }
                        catch
                        {

                            tran.Rollback();//如果执行不成功，发送异常，则执行rollback方法，回滚到事务操作开始之前。
                            conn.Close();
                            MessageBox.Show("删除失败");
                        }

                    }
                }

            }
               }
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            CaigouEntry cae = new CaigouEntry();
            using (SqlConnection conn = new SqlConnection(App.GetSqlConnection()))
            {
                conn.Open();
                using (SqlTransaction tran = conn.BeginTransaction()) //开始数据库事务。即创建一个事务对象tran  
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        cmd.Connection = conn;
                        cmd.Transaction = tran; //获取或设置将要其执行的事务  
                        try
                        {


                            for (int i = 0; i < dgvdo.RowCount; i++)
                            {
                              
                                    if (this.dgvdo.Rows[i].Cells["明细id"].Value != null && this.dgvdo.Rows[i].Cells["明细id"].Value.ToString() != "")
                                    {
                                        cae.deleteCaigouEntry(" CaigouEntryID = " + this.dgvdo.Rows[i].Cells["明细id"].Value.ToString(), conn, cmd);
                                    }
                                    dgvdo.Rows.Remove(dgvdo.Rows[i]);
                                    i -= 1;
                                

                            }

                            tran.Commit();
                            conn.Close();

                        }
                        catch
                        {

                            tran.Rollback();//如果执行不成功，发送异常，则执行rollback方法，回滚到事务操作开始之前。
                            conn.Close();
                            MessageBox.Show("保存失败");
                        }

                    }
                }

            }
        }

        private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
        {
            CaigouEntry cae = new CaigouEntry();
            using (SqlConnection conn = new SqlConnection(App.GetSqlConnection()))
            {
                conn.Open();
                using (SqlTransaction tran = conn.BeginTransaction()) //开始数据库事务。即创建一个事务对象tran  
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        cmd.Connection = conn;
                        cmd.Transaction = tran; //获取或设置将要其执行的事务  
                        try
                        {


                            for (int i = 0; i < dgvdo.RowCount; i++)
                            {

                                if (this.dgvdo.Rows[i].Cells["明细id"].Value != null && this.dgvdo.Rows[i].Cells["明细id"].Value.ToString() != "")
                                {
                                    cae.deleteCaigouEntry(" CaigouEntryID = " + this.dgvdo.Rows[i].Cells["明细id"].Value.ToString(), conn, cmd);
                                }
                                dgvdo.Rows.Remove(dgvdo.Rows[i]);
                                i -= 1;


                            }

                            tran.Commit();
                            conn.Close();

                        }
                        catch
                        {

                            tran.Rollback();//如果执行不成功，发送异常，则执行rollback方法，回滚到事务操作开始之前。
                            conn.Close();
                            MessageBox.Show("保存失败");
                        }

                    }
                }

            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否生成入库单?", "请确认信息", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                //验证数据
                StringBuilder message = new StringBuilder();
                if (this.dgvdo.RowCount == 0)
                {
                    MessageBox.Show("请添加商品！ ");
                    return;
                }
                //判断物料重复
                for (int i = 0; i < this.dgvdo.RowCount; i++)
                {
                    for (int j = i + 1; j < this.dgvdo.RowCount; j++)
                    {

                        if (dgvdo.Rows[i].Cells["商品id"].Value.ToString() == dgvdo.Rows[j].Cells["商品id"].Value.ToString())
                        {
                            MessageBox.Show("第" + (i + 1) + "行与第" + (j + 1) + "行重复！ ");
                            return;
                        }
                    }
                }

                if (comboBox2.SelectedIndex == 0)
                {
                    message.Append("请选择货主！\n ");
                }
                if (comboBox1.SelectedIndex == 0)
                {
                    message.Append("请选择仓库！\n ");
                }
                if (comboBox3.SelectedIndex == 0)
                {
                    message.Append("请选择供应商！\n ");
                }
                if (cmbcarrierid.SelectedIndex == 0)
                {
                    message.Append("请选择承运商！\n ");
                }



                //验证明细列表
                for (int i = 0; i < this.dgvdo.RowCount; i++)
                {
                    if (dgvdo.Rows[i].Cells["商品id"].Value == null || dgvdo.Rows[i].Cells["商品id"].Value.ToString() == "")
                    {
                        message.Append("第" + (i + 1) + "行未选择商品！\n ");
                    }
                    Double ddd = 0;
                    if (dgvdo.Rows[i].Cells["采购数量"].Value == null || dgvdo.Rows[i].Cells["采购数量"].Value.ToString() == "" || !Double.TryParse(dgvdo.Rows[i].Cells["采购数量"].Value.ToString(), out ddd))
                    {
                        message.Append("第" + (i + 1) + "行采购数量请填写数字！\n ");

                    }
                    Double ddd1 = 0;
                    if (dgvdo.Rows[i].Cells["采购价"].Value == null || dgvdo.Rows[i].Cells["采购价"].Value.ToString() == "" || !Double.TryParse(dgvdo.Rows[i].Cells["采购价"].Value.ToString(), out ddd1))
                    {
                        message.Append("第" + (i + 1) + "行采购价请填写数字！\n ");

                    }
                }
                if (message != null && message.ToString() != "")
                {
                    MessageBox.Show(message.ToString());
                    return;
                }
                //开始新增
                button2.Enabled = false;

                //Math.Round(45.367,2)  
                using (SqlConnection conn = new SqlConnection(App.GetSqlConnection()))
                {
                    conn.Open();
                    using (SqlTransaction tran = conn.BeginTransaction()) //开始数据库事务。即创建一个事务对象tran  
                    {
                        using (SqlCommand cmd = new SqlCommand())
                        {
                            cmd.Connection = conn;
                            cmd.Transaction = tran; //获取或设置将要其执行的事务  
                            // try
                            // {
                            //保存
                            Caigou cgd = new Caigou();


                            cgd.ZhiDanDate = DateTime.Now;
                            cgd.CaigouDate = DateTime.Parse(dateTimePicker1.Text.Trim());
                            if (userid > 0)
                            {
                                cgd.UserID = userid;
                                cgd.CaigourenID = userid;
                            }
                            else
                            {
                                cgd.UserID = App.AppUser.UserID;
                                cgd.CaigourenID = App.AppUser.UserID;
                            }

                            cgd.CaigouTypeID = App.caigouputong;
                            cgd.CaigouStatusID = App.guanbi;
                            cgd.SupplierID = int.Parse(comboBox2.SelectedValue.ToString());
                            cgd.SupplySupplierID = int.Parse(comboBox3.SelectedValue.ToString());
                            cgd.CarrierID = int.Parse(cmbcarrierid.SelectedValue.ToString());
                            cgd.StoreID = int.Parse(comboBox1.SelectedValue.ToString());



                            cgd.TuiHuoKeHu = textBox1.Text.Trim();
                            cgd.TuiHuoRemark = textBox3.Text.Trim();
                            cgd.Remark = txtbProduct.Text.Trim();
                            if (CaigouID11 > 0)
                            {
                                cgd.CaigouNumber = txtbOrderNumber.Text;
                                cgd.CaigouID = CaigouID11;
                                cgd.updateCaigou(cgd, conn, cmd);
                            }
                            else
                            {
                                cgd.CaigouNumber = cgd.MakeCaigouNumber(conn, cmd);
                                txtbOrderNumber.Text = cgd.CaigouNumber;
                                cgd.CaigouID = cgd.saveCaigou(cgd, conn, cmd);
                                CaigouID11 = cgd.CaigouID;
                            }

                            //生成入库单
                            InStock ins = new InStock();
                            //ins.InStockNumber;
                            ins.CaigouNumber = cgd.CaigouNumber;
                            ins.JieDanDate = DateTime.Now;
                            ins.InStockDate = DateTime.Now;
                            ins.UserID = App.AppUser.UserID;
                            ins.InStockTypeID = App.newstatus;
                            ins.InStockStatusID = App.newstatus;
                            ins.SupplierID = cgd.SupplierID;
                            ins.SupplySupplierID = cgd.SupplySupplierID;
                            ins.CarrierID = cgd.CarrierID;
                            //ins.ShouHuoID;
                            ins.StoreID = cgd.StoreID;
                            ins.TuiHuoKeHu = textBox1.Text;
                            ins.TuiHuoRemark = "";
                            ins.Remark = "";
                            ins.InStockID = ins.saveInStock(ins, conn, cmd);


                            //插入明细
                            for (int i = 0; i < this.dgvdo.Rows.Count; i++)
                            {
                                CaigouEntry cae = new CaigouEntry();
                                cae.CaigouID = cgd.CaigouID;
                                cae.ProdID = int.Parse(this.dgvdo.Rows[i].Cells["商品id"].Value.ToString());



                                cae.CaigouShuLiang = double.Parse(this.dgvdo.Rows[i].Cells["采购数量"].Value.ToString());
                                cae.Caigoujia = double.Parse(this.dgvdo.Rows[i].Cells["采购价"].Value.ToString());

                                cae.Remark = "";

                                if (this.dgvdo.Rows[i].Cells["明细id"].Value != null && this.dgvdo.Rows[i].Cells["明细id"].Value.ToString() != "")
                                {
                                    cae.CaigouEntryID = int.Parse(this.dgvdo.Rows[i].Cells["明细id"].Value.ToString());
                                    cae.updateCaigouEntry(cae, conn, cmd);

                                }
                                else
                                {
                                    int CaigouEntryid = cae.saveCaigouEntry(cae, conn, cmd);
                                    this.dgvdo.Rows[i].Cells["明细id"].Value = CaigouEntryid;
                                }

                                //生成入库单
                                InStockEntry inse = new InStockEntry();
                                //inse.InStockEntryID;
                                inse.InStockID = ins.InStockID;
                                inse.ProdID = cae.ProdID;
                                inse.ProdTypeID = int.Parse(this.dgvdo.Rows[i].Cells["商品种类id"].Value.ToString());
                                //inse.StorageID ;
                                inse.Batch = DateTime.Now.ToString("yyyy-MM-dd");
                                inse.ProduceDate = DateTime.Now;
                                inse.StockPinZhiID = App.newstatus;
                                inse.StockQtyYuBao = cae.CaigouShuLiang;
                                // inse.StockQty;
                                // inse.Remark;
                                inse.InStockEntryID = inse.saveInStockEntry(inse, conn, cmd);


                            }


                            tran.Commit();
                            conn.Close();

                            MessageBox.Show("生成成功");
                            this.Close();
                            //  }
                            //  catch
                            //  {

                            //       tran.Rollback();//如果执行不成功，发送异常，则执行rollback方法，回滚到事务操作开始之前。
                            //       conn.Close();
                            //      MessageBox.Show("保存失败");
                            //  }

                        }
                    }

                }
            }
        }

       // private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
     //   {

      //  }

    }
}
